package com.aya.mybaits.spring.config;

import org.springframework.core.io.Resource;
import org.springframework.core.io.support.PathMatchingResourcePatternResolver;
import org.springframework.core.io.support.ResourcePatternResolver;
import org.springframework.core.type.classreading.MetadataReader;
import org.springframework.core.type.classreading.MetadataReaderFactory;
import org.springframework.core.type.classreading.SimpleMetadataReaderFactory;

import java.io.IOException;
import java.util.HashSet;
import java.util.Set;
import java.util.stream.Collectors;

public class ScanBasePackage {
    private Resource[] wildcard;

    public void setWildcard(Resource[] wildcard) {
        this.wildcard = wildcard;
    }

    public String getPack() throws IOException, ClassNotFoundException {
        ResourcePatternResolver resolver = new PathMatchingResourcePatternResolver();
//        Resource[] resources = resolver.getResources("classpath*:"+wildcard+".class");
        MetadataReaderFactory metadataReaderFactory = new SimpleMetadataReaderFactory(resolver);
        Set<String> stringList = new HashSet<>();
        for (Resource resource : wildcard) {
            MetadataReader metadataReader = metadataReaderFactory.getMetadataReader(resource);
            stringList.add(Class.forName(metadataReader.getClassMetadata().getClassName()).getPackage().getName());
        }
        return stringList.stream().collect(Collectors.joining(","));
    }
}
